package com.chromatic.competition.view.notifications;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chromatic.competition.R;
import com.chromatic.competition.service.StabilityAIService;

public class PaintActivity extends AppCompatActivity {
    private EditText inputText;
    private FrameLayout imageContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paint);

        inputText = findViewById(R.id.inputText);
        Button generateButton = findViewById(R.id.generateButton);
        imageContainer = findViewById(R.id.imageContainer);

        generateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = inputText.getText().toString();
                generateImage(text);
            }
        });

        ImageView backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 调用系统返回操作
            }
        });
    }

    private void generateImage(String text) {
        StabilityAIService.generateImage(text, new StabilityAIService.ImageGenerationListener() {
            @Override
            public void onImageGenerated(String base64Image) {
                runOnUiThread(() -> {
                    // Decode the base64 image string and display it in the imageContainer
                    byte[] imageData = android.util.Base64.decode(base64Image, android.util.Base64.DEFAULT);
                    ImageView imageView = new ImageView(PaintActivity.this);
                    imageView.setImageBitmap(android.graphics.BitmapFactory.decodeByteArray(imageData, 0, imageData.length));

                    imageContainer.removeAllViews();
                    imageContainer.addView(imageView);
                });
            }

            @Override
            public void onError(String message) {
                runOnUiThread(() -> {
                    Toast.makeText(PaintActivity.this, message, Toast.LENGTH_SHORT).show();
                    Log.d("彩旗绘错误信息：",message);
                });
            }
        });
    }
}